package com.longxi.tianjintianbao.ui.activity.assetscheck;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponseWebPd;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataInventoryController;
import com.longxi.tianjintianbao.greedao.entity.Inventory;
import com.longxi.tianjintianbao.greedao.entity.InventoryChild;
import com.longxi.tianjintianbao.ui.adapter.multitype.inventory.InventoryViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.utils.AESUtil;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 获取盘点录入单
 * Created by cxw on & 2018/12/13
 */
public class AssetsWebServiceInventoryActivity extends BaseActivity {

    @BindView(R.id.etReceiptNumber)
    EditText etReceiptNumber;
    @BindView(R.id.btnDownload)
    Button btnDownload;

    private MultiTypeAdapter adapter;
    private Items items = new Items();
    int page = 0;
    int limit = 10;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_assets_web_service_inventory;
    }

    @Override
    public void initView() {
        super.initView();
        setTvLeft("返回");
        setTitle("资产盘点");
        initAdapter();
    }

    private void initAdapter() {
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            adapter.register(Inventory.class, new InventoryViewBinder(new InventoryViewBinder.OnClickListener() {
                @Override
                public void onClick(int position) {
                    Inventory inventory = (Inventory) items.get(position);
                    Intent intent = new Intent(AssetsWebServiceInventoryActivity.this, TestActivity.class);
                    intent.putExtra(AppConst.BILLID, inventory.getNumber());
                    startActivity(intent);
                }

                @Override
                public void onDelete(int position) {
                    Inventory inventory = (Inventory) items.get(position);
                    DataInventoryController.DeleteInventoryAndChild(inventory);
                    items.remove(position);

                    if(items.size() == 0){
                        mRefreshLayout.autoRefresh();
                    }else{
                        adapter.notifyItemRemoved(position);
                    }
                }
            }));
            mRvContent.setAdapter(adapter);
            adapter.setItems(items);
        }
    }

    @Override
    public void initListener() {
        super.initListener();
        btnDownload.setOnClickListener(v -> download());
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                getInventoryList();
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page=0;
                getInventoryList();
            }
        });
        mRefreshLayout.autoRefresh();
    }

    private void download() {
        String receiptNumber = etReceiptNumber.getText().toString().trim();
        if(TextUtils.isEmpty(receiptNumber)){
            MyUtils.showToast(etReceiptNumber.getHint().toString().trim());
            return;
        }

        showWaitingDialog("正在下载");

        String usernameApassword = "";
        try {
            usernameApassword = MyApplication.username + ",," + AESUtil.encrypt(MyApplication.password, "1234567890123456");
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject object = new JSONObject();
        try {
            object.put("type", "getdata");
            object.put("validate", usernameApassword);
            object.put("billtype", "inventory");
            object.put("billcode", receiptNumber);
            object.put("billdata", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().validate(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponseWebPd>(this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponseWebPd result) {
                if(result.getCode() != 0){
                    hideWaitingDialog();
                    MyUtils.showToast(result.getMsg());
                    return;
                }

                if(result.getData().contains("ERROR")){
                    hideWaitingDialog();
                    MyUtils.showToast(result.getData());
                    return;
                }

                String[] strings = result.getData().split("\r\n");
                if(strings.length < 3){
                    hideWaitingDialog();
                    return;
                }
                String[] stringInventory = strings[0].split(",");
                Inventory inventory = new Inventory();
                inventory.number = stringInventory[0];
                inventory.isupload = stringInventory[1];
                Inventory newInventory = DataInventoryController.insertInventory(inventory);
                for (int i = 2; i < strings.length; i++) {

                    String[] pd = strings[i].split(",");
                    InventoryChild inventoryChild = new InventoryChild();
                    inventoryChild.iid = newInventory.getId();
                    inventoryChild.number = pd[0];
                    inventoryChild.cagegory = pd[1];
                    inventoryChild.name = pd[2];
                    inventoryChild.department = pd[3];
                    inventoryChild.location = pd[4];
                    inventoryChild.gps = pd[5];

                    try {
                        inventoryChild.booknum = Double.parseDouble(pd[6]);
                    } catch (NumberFormatException e) {
                        inventoryChild.booknum = 0.0;
                    }

                    try {
                        inventoryChild.inventorynum = Double.parseDouble(pd[7]);
                    } catch (NumberFormatException e) {
                        inventoryChild.inventorynum = 0.0;
                    }

                    inventoryChild.specifications = pd[8];
                    inventoryChild.images = pd[9];
                    inventoryChild.unit = pd[10];
                    if(inventoryChild.inventorynum > 0){
                        inventoryChild.isdraft = "2";
                    }else{
                        inventoryChild.isdraft = "0";
                    }
                    inventoryChild.state = "0";
                    DataInventoryController.insertInventoryChildDao(inventoryChild);
                }

                hideWaitingDialog();
                mRefreshLayout.autoRefresh();

            }
        });
    }

    private void getInventoryList(){
        List<Inventory> list = DataInventoryController.SearchInventory(page, limit);
        if(page == 0){
            items.clear();
        }
        items.addAll(list);
        adapter.notifyDataSetChanged();
        if(list.size() < limit){
            MyUtils.showToast("没有更多数据了");
        }
        if(items.size() > 0){
            for (Inventory inventory : list) {
                long conut = DataInventoryController.SearchInventoryByIsdraft(inventory);
                if(conut > 0){
                    inventory.setState("未完成");
                }else{
                    inventory.setState("已完成");
                }
            }

            hideLoading();
        }else{
            showNoData();
        }
        if(mRefreshLayout.isRefreshing()){
            mRefreshLayout.finishRefresh();
        }

        if(mRefreshLayout.isLoading()){
            mRefreshLayout.finishLoadMore();
        }
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.items = null;
        this.adapter = null;
    }
}
